#pragma once
#include <iostream>
#include <functional>
#include <unistd.h>
#include <string>
#include"InetAddr.hpp"

class Reactor;
class Connection;
using func_t = std::function<void(Connection*)>;


class Connection
{
  public:
    Connection(int sockfd)
        :_sockfd(sockfd)
        ,_R(nullptr)
    {}

    int Sockfd()
    {
        return _sockfd;
    }

    void SetEvents(int events)
    {
        _events = events;
    }

    uint32_t Events()
    {
        return _events;
    }

    void Register(func_t recver,func_t sender,func_t excepter)
    {
        _recver = recver;
        _sender = sender;
        _excepter = excepter;
    }

     void SetSelf(Reactor *R)
    {
        _R = R;
    }

    void AppendInBuffer(const string &buffer)//临时拷贝将亡值
    {
        _inbuffer += buffer;
    }

    void AppendOutBuffer(const string &buffer)
    {
        _outbuffer += buffer;
    }

    string& Outbuffer()//引用返回可以修改
    {
        return _outbuffer;
    }
    string& Inbuffer()
    {
        return _inbuffer;
    }

    void OutbufferRemove(int n)
    {
        _outbuffer.erase(0,n);
    }

    bool OutbufferEmpty()
    {
        return _outbuffer.empty();
    }

    void Close()
    {
        if(_sockfd>=0)
            ::close(_sockfd);
    }
    
    ~Connection()
    {

    }





  private:
    int _sockfd;
    //每个Connection中都有接受和发送缓冲区
    std::string _inbuffer;
    std::string _outbuffer;
    InetAddr _addr;

    uint32_t _events;//关系的事件的集合

  public:  
    func_t _recver;
    func_t _sender;
    func_t _excepter;//异常处理
    Reactor* _R;//可以通过这个指针访问反应堆中的方法


};